package com.ncucoder.client.consumer;

import com.alibaba.fastjson.JSON;
import com.ncucoder.client.constant.OrderConstants;
import com.ncucoder.client.model.Goods;
import com.ncucoder.client.model.Message;
import com.ncucoder.client.model.Order;
import com.ncucoder.client.service.GoodsService;
import com.ncucoder.client.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Map;

/**
 * @author <a href="https://www.ncucoder.com">hsowan</a>
 * @since 2019-01-19 20:48
 */
@Component
public class OrderConsumer {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderService orderService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "order-queue", durable = "true"),
            exchange = @Exchange(name = "order-exchange", type = "topic"),
            key = "order.*"
    ))
    @RabbitHandler
    public void onMessage(@Payload String message, @Headers Map<String, Object> headers, Channel channel) throws IOException {
        Message m = JSON.parseObject(message, Message.class);
        System.out.println(m.toString());

        String messageId = JSON.parseObject(m.getBody(), Order.class).getMessageId();

        Goods goods = goodsService.getById((long) 1);
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        int count = goods.getCount();
        if (count > 0){
            goods.setCount(count - 1);
            goodsService.saveOrUpdate(goods);

            Order order = orderService.getByMessageid(messageId);
            order.setStatus(OrderConstants.DONE);
            order.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            orderService.saveOrUpdate(order);

        }
        channel.basicAck(deliveryTag, false);
    }
}
